package com.yt.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库表结构工具类
 *
 * @author 
 * @Date 2025-11-13
 */
@Component
public class TableStructureUtils {

    @Autowired
    private DataSource dataSource;

    /**
     * 获取表结构信息
     *
     * @param tableName 表名
     * @return 表结构信息列表
     * @throws SQLException
     */
    public List<Map<String, Object>> getTableStructure(String tableName) throws SQLException {
        List<Map<String, Object>> structureList = new ArrayList<>();
        
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            
            // 获取列信息
            try (ResultSet columns = metaData.getColumns(null, null, tableName, null)) {
                while (columns.next()) {
                    Map<String, Object> columnInfo = new HashMap<>();
                    columnInfo.put("columnName", columns.getString("COLUMN_NAME"));      // 列名
                    columnInfo.put("typeName", columns.getString("TYPE_NAME"));          // 数据类型
                    columnInfo.put("columnSize", columns.getInt("COLUMN_SIZE"));         // 列大小
                    columnInfo.put("nullable", columns.getInt("NULLABLE") == DatabaseMetaData.columnNullable ? "是" : "否"); // 是否可为空
                    columnInfo.put("remarks", columns.getString("REMARKS"));             // 列注释
                    columnInfo.put("columnDef", columns.getString("COLUMN_DEF"));        // 默认值
                    columnInfo.put("ordinalPosition", columns.getInt("ORDINAL_POSITION")); // 列序号
                    
                    structureList.add(columnInfo);
                }
            }
        }
        
        return structureList;
    }
}